package com.flea.web.controller;

import com.flea.model.UploadFile;
import com.flea.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@Controller
public class FileController {

    @Resource
    private UploadFileService uploadFileService;

    @GetMapping("/file/{id}")
    public void readFile(@PathVariable Integer id, HttpServletResponse response) {
        UploadFile uploadFile = uploadFileService.findUploadFile(id);
        File file = uploadFileService.findLocalFile(uploadFile);
        response.setContentType(uploadFile.getContentType());
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream();) {
            byte[] buffer = new byte[1024]; // 图片文件流缓存池
            while (is.read(buffer) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe) {
            log.warn("reading {} failed", id, ioe);
        }
    }

//    public void test{
//        InputStream is;
//        OutputStream os;
//        try {
//            is = new FileInputStream(file);
//            os = response.getOutputStream();
//            byte [] buffer = new byte[1024]; // 图片文件流缓存池
//            while(is.read(buffer) != -1){
//                os.write(buffer);
//            }
//        }catch (IOException e){
//            System.out.println(e);
//        }finally {
//            if(is!=null){
//                is.close();;
//            }
//            if(os!=null){
//                os.close();
//            }
//        }
//
//    }

}
